package com.netty.websocket;

import com.alibaba.fastjson.JSONObject;
import com.topsoft.common.MiscHelper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 处理 Http 请求
 * @author waylau.com
 * @date 2015-3-26 
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> { //1
    private final String wsUri;
    private Logger logger = LogManager.getLogger("[netty]"+getClass().getName());

    public HttpRequestHandler(String wsUri) {
        super();
        this.wsUri = wsUri;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        try {
            Channel channel = ctx.channel();
            //QueryStringDecoder decoder = new QueryStringDecoder(request.uri().replace("/?",""));
            String __url = request.uri();
            __url = request.uri().substring(__url.indexOf("?") + 1);
            JSONObject parameters = MiscHelper.urlParameter2Map(__url);
            String queue = parameters.getString("queue");//得到队列名

            String isConfirm2Producer = parameters.getString("isConfirm2Producer");
            isConfirm2Producer = isConfirm2Producer == null || isConfirm2Producer.equals("") ? "true" : isConfirm2Producer;

            String isServerRecv2Producer = parameters.getString("isServerRecv2Producer");
            isServerRecv2Producer = isServerRecv2Producer == null || isServerRecv2Producer.equals("") ? "false" : isServerRecv2Producer;



            String isSendIsConfirm = parameters.getString("isSendIsConfirm");
            isSendIsConfirm = isSendIsConfirm == null || isSendIsConfirm.equals("") ? "false" : isSendIsConfirm;


            JSONObject errJsonMsg = null;
            if (MiscHelper.isNull(queue)) {
                errJsonMsg = new JSONObject(true);
                errJsonMsg.put("__type", "error");
                errJsonMsg.put("number", "E201");
                errJsonMsg.put("info", "连接地址url中参数queue的值不能为空");
                //channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(errJsonMsg)));
                //throw new Exception("url地址中，必须有队列参数queue=xxx。 例：ws://192.168.8.108:9001?queue=dbcon");
            } else {
            }

            request.setUri(wsUri);
            ctx.fireChannelRead(request.retain());

            Attribute<WebSocketHandler> attrWebSocketHandler = channel.attr(AttributeKey.valueOf("webSocketHandler"));
            WebSocketHandler webSocketHandler = attrWebSocketHandler.get();
            if (webSocketHandler != null) {
                webSocketHandler.queue = queue;
                webSocketHandler.isConfirm2Producer   = isConfirm2Producer != null && isConfirm2Producer.toLowerCase().equals("true") ? true : false;
                webSocketHandler.isServerRecv2Producer= isServerRecv2Producer != null && isServerRecv2Producer.toLowerCase().equals("true") ? true : false;
                webSocketHandler.isSendIsConfirm      = isSendIsConfirm != null && isSendIsConfirm.toLowerCase().equals("true") ? true : false;
                webSocketHandler.parameters = parameters;
                webSocketHandler.errJsonMsg = errJsonMsg;
                webSocketHandler.afterAdd(channel);

                Attribute<String> attrQueue= channel.attr(AttributeKey.valueOf("queue"));
                attrQueue.set(queue);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private static void send100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
        ctx.writeAndFlush(response);
    }

//	@Override
//	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
////    	Channel channel = ctx.channel();
////        logger.debug("Client:"+channel.remoteAddress()+"异常"+cause.getMessage());
//        // 当出现异常就关闭连接
//        cause.printStackTrace();
//        ctx.close();
//	}
}
